import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import { getHttpCodes } from '@/utils/httpCodes'
// create an axios instance
const service = axios.create({
   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    console.log(store.getters.token)
    console.log(getToken())
    if (getToken()) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    return response
  },
  error => {
    if (error && error.response) {
      if (error.request.responseType === 'blob') {
        var reader = new FileReader()
        reader.readAsText(error.response.data, 'utf-8')
        reader.onload = function() {
          var data = JSON.parse(reader.result)
          var httpCode = error.response.status
          var dataCode = data.code
          var desc = data.desc
          var httpCodes = getHttpCodes()
          for (let index = 0; index < httpCodes.length; index++) {
            const ele = httpCodes[index]
            if (ele.httpCode === httpCode && ele.dataCode === dataCode && ele.desc === desc) {
              if (ele.tipType === 'tip') {
                Message({
                  message: ele.tip,
                  type: 'error',
                  duration: 3000
                })
              } else if (ele.tipType === 'dialog') {
                MessageBox.confirm(ele.tip, {
                  confirmButtonText: '退出',
                  cancelButtonText: '取消',
                  type: 'warning',
                  showClose: false,
                  customClass: 'rmsg01',
                  confirmButtonClass: 'confirm',
                  cancelButtonClass: 'cancal'
                }).then(() => {
                  store.dispatch('user/backlogin').then(() => {
                    router.push('login')
                  })
                }).catch(action => { })
              }
            }
          }
        }
        return Promise.reject(error.response)
      } else {
        return errCode(error)
      }
    } else {
      var msg = '连接服务器错误'
      MessageBox.confirm(msg, {
        confirmButtonText: '退出',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false,
        customClass: 'rmsg01',
        confirmButtonClass: 'confirm',
        cancelButtonClass: 'cancal'
      }).then(() => {
        store.dispatch('user/backlogin').then(() => {
          router.push('login')
        })
      }).catch(action => { })
      return Promise.reject(msg)
    }
  }
)

var isTip = 0
function errCode(error) {
  var httpCodes = getHttpCodes()
  var httpCode = error.response.status

  error.response.data.errors.forEach((item) => {
    var dataCode = item.code
    var desc = item.desc
    console.log(item)

    if (httpCode === '401' && dataCode === '4104' && desc === 'token is invalid error') {
      if (isTip === 0) {
        isTip = 1
      } else {
        return Promise.reject(error.response)
      }
    }

    for (let index = 0; index < httpCodes.length; index++) {
      const ele = httpCodes[index]
      if (ele.httpCode === httpCode && ele.dataCode === dataCode && ele.desc === desc) {
        if (ele.tipType === 'tip') {
          Message({
            message: ele.tip,
            type: 'error',
            duration: 3000
          })
        } else if (ele.tipType === 'dialog') {
          console.log(33)
          MessageBox.confirm(ele.tip, {
            confirmButtonText: '退出',
            cancelButtonText: '取消',
            type: 'warning',
            showClose: false,
            // showCancelButton:false,
            customClass: 'rmsg01',
            confirmButtonClass: 'confirm',
            closeOnClickModal: false,
            cancelButtonClass: 'cancal'
          }).then(() => {
            isTip = 0
            store.dispatch('user/backlogin').then(() => {
              router.push('login')
            })
          }).catch(action => { isTip = 0 })
        }
        return Promise.reject(error.response)
      }
    }
  })

  return Promise.reject(error.response)
}
export default service
